package com.ebix.sample.servlet;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;

import javax.naming.NamingException;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import com.ebix.sample.dao.helper.DAOHelper;

/**
 * Servlet implementation class AppBoot. It's not really related to our
 * architecture, but it's there to help use to set up the database for the
 * sample
 */
public class AppBoot extends HttpServlet {
	private static final long serialVersionUID = 145655622654265L;

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {

		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ResourceBundle b = ResourceBundle//
					.getBundle("com.ebix.sample.servlet.Database-Schema");
			con = DAOHelper.INSTANCE.getConnection();
			// test if database exists
			try {
				ps = con.prepareStatement(b.getString("test"));
				rs = ps.executeQuery();
				rs.next();// everything is ok
			} catch (Exception xe) {
				DAOHelper.INSTANCE.close(ps);
				System.out.println(">>>>>>>>>>>creating schema<<<<<<<<<<<");
				String[] creates = new String[] { //
				"create-usuario", "create-segurado",//
						"create-veiculo",//
						"create-marca",//
						"create-corretor",//
						"create-cotacao",//
						"create-proposta"//
				};
				for (String k : creates) {
					ps = con.prepareStatement(b.getString(k));
					ps.executeUpdate();
					DAOHelper.INSTANCE.close(ps);
				}
				String inserts[] = new String[] {//
				/* == */"insert-wis-user",//
						"insert-wis-broker",//
						"insert-wis-manufacturer",//
						"insert-wis-vehicle"//
				};
				for (String ins : inserts) {
					ps = con.prepareStatement(b.getString(ins));
					ps.executeUpdate();
					ps.close();
				}
			} finally {
				DAOHelper.INSTANCE.close(con, ps, rs);
			}
		} catch (NamingException e) {
			throw new ServletException(e);
		} catch (SQLException e) {
			throw new ServletException(e);
		} finally {
			DAOHelper.INSTANCE.close(con, ps, rs);
		}
	}
}
